#include <stdint.h>

/*
 * debounce
 * A function like this will debounce up to eight input pins.
 * Simply call it each time the raw state is reread
 * and use the returned value for the debounced signals.
 * To require three or more consecutive readings be the same,
 * simply replace previous with two or more prior states.
 *
 * 消抖
 * 这样的函数最多可对八个输入引脚进行消抖。
 * 只需在每次重新读取原始状态时调用该函数
 * 并将返回值用于去抖信号。
 * 如需三个或更多连续读数相同，
 * 只需将 previous 替换为两个或更多先前状态即可。
 */
uint8_t debounce(uint8_t current)
{
    static uint8_t asserted = 0x00;
    static uint8_t previous = 0x00;
    /* 
     * Compare the current and previous states of each input.
     * 比较每个输入引脚的当前状态和上一次的状态。
     */
    asserted |= (previous & current); // Assert newly "on" inputs. 将稳定输入 "1" 引脚对应 bit 置 1
    asserted &= (previous | current); // Clear newly "off" inputs. 将稳定输入 "0" 引脚对应 bit 清 0
    /*
     * Update the history.
     * 更新历史状态。
     */
    previous = current;
    /*
     * Return the debounced inputs to the caller.
     * 将已经消除抖动过后的输入返回给调用者。
     */
    return (asserted);
} /* debounce() */
